<template>
  <div class="adec-container">
    <h2 class="adec-title">连退历史跑偏</h2>

    <!-- 筛选与信息区域 -->
    <div class="adec-filter-info-area">
       <!-- Date Picker Row Item -->
       <div class="adec-filter-item">
         <span class="adec-label">时间范围:</span>
         <el-date-picker
           v-model="dateTimeRange"
           type="datetimerange"
           range-separator="至"
           start-placeholder="开始时间"
           end-placeholder="结束时间"
           size="small"
           format="YYYY-MM-DD HH:mm:ss"
           value-format="YYYY-MM-DD HH:mm:ss"
           class="adec-date-picker"
         />
       </div>

       <!-- Buttons Row Item (Pushed Right) -->
       <div class="adec-filter-right">
         <el-button type="primary" size="small" @click="fetchData">获取选定时间</el-button>
         <el-button size="small" @click="setDateRange('day')">一日</el-button>
         <el-button size="small" @click="setDateRange('week')">一周</el-button>
         <el-button size="small" @click="setDateRange('month')">一月</el-button>
       </div>

       <!-- Suggestion Row Item (Full Width) -->
       <div class="adec-suggestion">
         <span class="adec-label">处理建议:</span>
         <span class="adec-suggestion-text">{{ processingSuggestion }}</span>
       </div>
    </div>

    <!-- 统计表格 -->
    <div class="adec-stats-table-container">
      <el-table :data="statsTableData" border style="width: 100%" size="small" :header-cell-style="statsHeaderStyle">
        <el-table-column prop="metric" label="指标" width="100" fixed="left" align="center" />
        <el-table-column v-for="i in 15" :key="'cpc_stats_'+i" :label="'CPC'+ (i === 7 ? '8A' : (i >= 8 ? i : i))" align="center">
          <el-table-column :prop="'cpc'+i+'_mean'" label="均值" width="70" align="center">
            <template #default="scope">
              {{ scope.row['cpc'+i+'_mean'] != null ? scope.row['cpc'+i+'_mean'].toFixed(1) : '-' }}
            </template>
          </el-table-column>
          <el-table-column :prop="'cpc'+i+'_stddev'" label="标准差" width="70" align="center">
             <template #default="scope">
              {{ scope.row['cpc'+i+'_stddev'] != null ? scope.row['cpc'+i+'_stddev'].toFixed(1) : '-' }}
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <!-- 图表网格 -->
    <div class="adec-chart-grid">
       <div v-for="i in 15" :key="'cpc_chart_'+i" class="adec-chart-item">
         <div class="adec-chart-title">{{ 'CPC'+ (i === 7 ? '8A' : (i >= 8 ? i : i)) }} ROLL POS</div>
         <div class="adec-chart" :ref="el => { if (el) cpcChartRefs[i-1] = el as HTMLElement }"></div>
       </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts/core';
import {
  ScatterChart,
  LineChart,
  ScatterSeriesOption,
  LineSeriesOption
} from 'echarts/charts';
import {
  TooltipComponent,
  GridComponent,
  TitleComponent,
  VisualMapComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import type { EChartsOption } from 'echarts';

// Register ECharts components
echarts.use([
  TooltipComponent,
  GridComponent,
  TitleComponent,
  VisualMapComponent,
  ScatterChart,
  LineChart,
  CanvasRenderer
]);

// --- Reactive Data ---
const dateTimeRange = ref<[string, string] | null>(['2024-02-29 0:32:23', '2024-03-07 0:32:23']); // Default from image
const processingSuggestion = ref('建议CPC1向操作侧调节27mm、建议CPC4向传动侧调节35mm、建议CPC8A向传动侧调节49mm、建议CPC8向传动侧调节38mm、建议CPC9向传动侧调节22mm、建议CPC11向传动侧调节39mm、建议CPC12向传动侧调节25mm、建议CPC14向传动侧调节25mm'); // Default from image

// Statistics Table Data (Structure needs to match columns)
const statsTableData = reactive([
  {
    metric: '纠偏缸位置',
    cpc1_mean: -27.3, cpc1_stddev: 0.5,
    cpc2_mean: 0.0, cpc2_stddev: 2.0,
    cpc3_mean: -2.0, cpc3_stddev: 7.1,
    cpc4_mean: 34.9, cpc4_stddev: 7.8,
    cpc5_mean: 14.5, cpc5_stddev: 6.0,
    cpc6_mean: 3.1, cpc6_stddev: 7.1,
    cpc7_mean: 12.3, cpc7_stddev: 3.4, // This corresponds to CPC8A in image
    cpc8_mean: 48.8, cpc8_stddev: 1.5, // This corresponds to CPC8 in image
    cpc9_mean: 37.9, cpc9_stddev: 19.8,
    cpc10_mean: 22.1, cpc10_stddev: 17.8,
    cpc11_mean: -13.4, cpc11_stddev: 7.2,
    cpc12_mean: 39.2, cpc12_stddev: 3.9,
    cpc13_mean: 24.9, cpc13_stddev: 6.1,
    cpc14_mean: -9.5, cpc14_stddev: 4.9,
    cpc15_mean: 25.2, cpc15_stddev: 5.8
    // cpc16_mean: -4.6, cpc16_stddev: 2.5 // Index mapping needs care if labels don't match index 1:1
    // cpc17_mean: 2.0, cpc17_stddev: 2.0
  },
  {
    metric: '带钢位置',
    cpc1_mean: 0.0, cpc1_stddev: 0.4,
    cpc2_mean: -0.7, cpc2_stddev: 1.1,
    cpc3_mean: 0.0, cpc3_stddev: 0.3,
    cpc4_mean: 1.0, cpc4_stddev: 0.3,
    cpc5_mean: 0.2, cpc5_stddev: 0.3,
    cpc6_mean: 0.2, cpc6_stddev: 0.4,
    cpc7_mean: -5.7, cpc7_stddev: 1.8, // CPC8A
    cpc8_mean: -21.9, cpc8_stddev: 4.8, // CPC8
    cpc9_mean: -3.1, cpc9_stddev: 4.4,
    cpc10_mean: -1.4, cpc10_stddev: 4.0,
    cpc11_mean: 0.0, cpc11_stddev: 1.7,
    cpc12_mean: -7.1, cpc12_stddev: 1.4,
    cpc13_mean: 0.0, cpc13_stddev: 1.9,
    cpc14_mean: 0.1, cpc14_stddev: 1.9,
    cpc15_mean: 0.2, cpc15_stddev: 2.1
    // cpc16_mean: 0.1, cpc16_stddev: 2.0
    // cpc17_mean: 0.1, cpc17_stddev: 2.0
  }
]);

// Chart Refs and Instances
const cpcChartRefs = ref<HTMLElement[]>([]);
let cpcChartInstances: (echarts.ECharts | null)[] = [];

// --- Styles ---
const statsHeaderStyle = { // Style for stats table header
  background: '#eef1f6', // Light background similar to ActualPerformanceRollDeviation
  color: '#606266',
  fontWeight: '500'
};

// --- Methods ---
const fetchData = () => {
  ElMessage.info('获取选定时间数据...');
  console.log('获取数据范围:', dateTimeRange.value);
  // TODO: Implement actual data fetching based on dateTimeRange
  // Update statsTableData and regenerate chart data
  nextTick(() => {
     initCharts(); // Reinitialize charts with new data
  });
};

const setDateRange = (type: 'day' | 'week' | 'month') => {
  const end = new Date();
  let start = new Date();
  if (type === 'day') {
    start.setDate(end.getDate() - 1);
  } else if (type === 'week') {
    start.setDate(end.getDate() - 7);
  } else if (type === 'month') {
    start.setMonth(end.getMonth() - 1);
  }

  const formatDate = (date: Date): string => {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      const h = String(date.getHours()).padStart(2, '0');
      const min = String(date.getMinutes()).padStart(2, '0');
      const s = String(date.getSeconds()).padStart(2, '0');
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
  };

  dateTimeRange.value = [formatDate(start), formatDate(end)];
  fetchData(); // Fetch data for the new range
};

const generateMockChartSeriesData = (chartIndex: number): { blueDots: [number, number][], yellowLine: [number, number][] } => {
  const blueDots: [number, number][] = [];
  const yellowLine: [number, number][] = [];
  const numPoints = 100 + Math.floor(Math.random() * 100); // Variable number of points

  for (let i = 0; i < numPoints; i++) {
    const x = i; // Simple index as x-axis
    const yBlue = Math.random() * 200 - 100; // Range -100 to 100
    blueDots.push([x, yBlue]);

    // Add yellow line data for some charts based on image
    if ([0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14].includes(chartIndex)) { // Indices where yellow line seems present
        let yYellow = 0; // Default to 0
        if (chartIndex === 7 || chartIndex === 8 || chartIndex === 12 ) { // More variation for CPC8A, CPC9, CPC13
            yYellow = Math.random() * 30 - 15; // Small random variation around 0
        }
         if (chartIndex === 5 && Math.random() < 0.1) { // CPC6 occasional spike
             yYellow = Math.random() * 80 - 40;
         }
         if (chartIndex === 6 && Math.random() < 0.05) { // CPC7 occasional spike
             yYellow = Math.random() * 100 - 50;
         }
        yellowLine.push([x, yYellow]);
    }
  }
  return { blueDots, yellowLine };
};

const initCharts = () => {
  disposeCharts(); // Dispose previous instances
  cpcChartInstances = [];

  cpcChartRefs.value.forEach((chartRef, index) => {
    if (chartRef) {
      const chartInstance = echarts.init(chartRef);
      const { blueDots, yellowLine } = generateMockChartSeriesData(index);

      const option: EChartsOption = {
        backgroundColor: '#0a1a3a', // Dark background for charts
        grid: {
          left: '10%',
          right: '5%',
          top: '15%',
          bottom: '15%'
        },
        tooltip: {
          trigger: 'axis', // Show tooltip on hover
          axisPointer: {
            type: 'cross'
          },
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'value', // Assuming X is continuous value like time or sequence
          splitLine: { show: false },
          axisLabel: {
            color: '#ccc', // Light color for axis labels
            fontSize: 10
          },
          axisLine: {
              lineStyle: {
                  color: '#3a5a8a' // Axis line color
              }
          }
        },
        yAxis: {
          type: 'value',
          min: -100,
          max: 100,
          name: '纠偏辊调节量%',
          nameTextStyle: {
            color: '#ccc',
            fontSize: 10,
            align: 'left'
          },
          splitLine: {
            lineStyle: {
              color: '#3a5a8a', // Darker grid lines
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#ccc',
            fontSize: 10
          },
           axisLine: {
              show: true,
              lineStyle: {
                  color: '#3a5a8a'
              }
          }
        },
        series: [
          {
            name: '调节量',
            type: 'scatter',
            symbolSize: 4,
            data: blueDots,
            itemStyle: {
              color: '#5470c6' // Blue color for dots
            }
          } as ScatterSeriesOption,
          // Conditionally add yellow line series
          ...(yellowLine.length > 0 ? [{
            name: '基准?', // Or actual meaning
            type: 'line' as const, // Use const assertion for type literal
            symbol: 'none',
            smooth: false,
            data: yellowLine,
            lineStyle: {
              color: '#fac858', // Yellow color
              width: 1.5
            }
          } as LineSeriesOption] : []) // Cast second series
        ] as EChartsOption['series'] // Cast the whole array to the expected type
      };

      chartInstance.setOption(option);
      cpcChartInstances.push(chartInstance);
    }
  });
};

const disposeCharts = () => {
  cpcChartInstances.forEach(chart => chart?.dispose());
  cpcChartInstances = [];
};

const handleResize = () => {
  cpcChartInstances.forEach(chart => chart?.resize());
};

// --- Lifecycle Hooks ---
onMounted(() => {
  nextTick(() => {
      initCharts();
  });
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  disposeCharts();
});

</script>

<style scoped>
.adec-container {
  padding: 15px;
  background-image: linear-gradient(to top, white, #e6f0ff); /* Consistent light gradient */
  /* background-image: linear-gradient(to top, white, #2c69e8); /* Use if exact match needed */
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  font-family: 'Microsoft YaHei', sans-serif;
}

.adec-title {
  margin: 0 0 15px 0;
  color: #303133;
  text-align: center;
  font-size: 20px;
  font-weight: 600;
}

/* Filter/Info Area */
.adec-filter-info-area {
  display: flex;
  /* justify-content: space-between; */
  /* align-items: flex-start; */ /* Changed to center for vertical alignment */
  align-items: center; /* Vertically center items on the first line */
  margin-bottom: 15px;
  padding: 10px 15px;
  background-color: rgba(245, 247, 250, 0.85); /* Slightly opaque background */
  border-radius: 4px;
  flex-wrap: wrap; /* Allow wrapping on smaller screens */
  gap: 10px;
}

.adec-filter-left {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

/* New style for generic filter item */
.adec-filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.adec-filter-right {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0; /* Prevent shrinking */
    /* padding-top: 4px; */ /* Removed, align-items: center handles vertical */
    margin-left: auto; /* Pushes this block to the right */
}

.adec-label {
  color: #606266;
  font-size: 12px;
  margin-right: 8px;
  white-space: nowrap;
}

.adec-date-picker {
    width: 360px; /* Adjust width as needed */
}

.adec-suggestion {
    display: flex;
    align-items: baseline;
    width: 100%; /* Make suggestion take full width to wrap */
    margin-top: 8px; /* Add some space above the suggestion text */
}

.adec-suggestion-text {
    font-size: 12px;
    color: #e6a23c; /* Orange color for suggestion */
    font-weight: 500;
    line-height: 1.4;
}

/* Use smaller size for date picker */
:deep(.adec-date-picker.el-input__wrapper) {
    height: 28px;
    line-height: 28px;
}
:deep(.adec-date-picker .el-range-input),
:deep(.adec-date-picker .el-range-separator) {
    height: 26px !important;
    line-height: 26px !important;
    font-size: 12px !important;
}

/* Stats Table */
.adec-stats-table-container {
  margin-bottom: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden; /* Clip table borders */
}

:deep(.el-table th.el-table__cell),
:deep(.el-table td.el-table__cell) {
    padding: 5px 0; /* Reduced padding for denser table */
}
:deep(.el-table--small .el-table__cell) {
     font-size: 12px;
}

/* Chart Grid */
.adec-chart-grid {
  flex-grow: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Responsive grid */
  gap: 10px;
  overflow-y: auto; /* Allow grid to scroll if needed */
  min-height: 300px; /* Ensure grid has some height */
  padding: 5px; /* Add padding around the grid */
}

.adec-chart-item {
  border: 1px solid #3a5a8a; /* Border matching chart axis color */
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #0a1a3a; /* Dark background for chart item */
  min-height: 180px; /* Min height for each chart item */
}

.adec-chart-title {
  padding: 5px 8px;
  font-size: 11px;
  font-weight: bold;
  color: #ccc; /* Light title color */
  background-color: #1c2d5a; /* Slightly lighter dark background for title */
  text-align: center;
  flex-shrink: 0;
  border-bottom: 1px solid #3a5a8a;
}

.adec-chart {
  flex-grow: 1; /* Chart takes remaining space */
}

</style>